import { TOKEN_KEY, USERINFO_KEY, LOGINSHOW_KEY, MOBILE_KEY } from '@/enums/cacheEnums';
import { defineStore } from 'pinia';
import cache from '@/utils/cache';

interface UserState {
    userInfo: string;
    token: string | null;
    temToken: string | null;
    loginshow: string | null;
    mobile: string | null;
    audioplay: number;
}

// 修正了 typo，将 UserSate 改为 UserState
export const useUserStore = defineStore('userStore',{
    id: 'userStore',
    state: (): UserState => {
        return {
            userInfo: cache.get(USERINFO_KEY) || '',
            token: cache.get(TOKEN_KEY) || '',
            temToken: null,
            loginshow: cache.get(LOGINSHOW_KEY) || '',
            mobile: cache.get(MOBILE_KEY) || '',
            audioplay: 0,
        };
    },
    getters: {
        // 明确指定 state 参数的类型为 UserState
        isLogin: (state: UserState) => !!state.token
    },
    actions: {
        setPlay() {
            this.audioplay = 1;
        },
        setUser(userInfo: any) {
            this.userInfo = JSON.stringify(userInfo);
            cache.set(USERINFO_KEY, this.userInfo);
            // 修正了缓存键，将 USERINFO_KEY 改为 MOBILE_KEY
            this.mobile = userInfo.mobile;
            cache.set(MOBILE_KEY, this.mobile);
        },
        login(token: string) {
            this.token = token;
            cache.set(TOKEN_KEY, this.token);
        },
        setLoginShow(e: string) {
            // 登录弹窗的状态
            this.loginshow = e;
            cache.set(LOGINSHOW_KEY, this.loginshow);
        },
        logout() {
            // mobile 置空
            this.mobile = null;
            // 修正了缓存键，将 LOGINSHOW_KEY 改为 MOBILE_KEY
            cache.set(MOBILE_KEY, this.mobile);

            // token 置空
            this.token = null;
            cache.set(TOKEN_KEY, this.token);

            // 用户信息置空
            this.userInfo = '';
            cache.set(USERINFO_KEY, this.userInfo);

            // 登录弹窗的状态
            this.loginshow = null;
            cache.set(LOGINSHOW_KEY, this.loginshow);
        },
        clearMobile() {
            this.mobile = null;
            cache.set(MOBILE_KEY, this.mobile);
        },
    }
});